package com.cqx.collection.scheduler;

import com.cqx.collection.web.vo.HeartBeatVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 推送数据
 **/
@Component
public class HeartBeatScheduler {

    private static Logger logger= LoggerFactory.getLogger(HeartBeatScheduler.class);

    @Value("${blender.id}")
    private String blenderId;

    @Value("${blender.url}")
    private String blenderUrl;

    @Value("${blender.line}")
    private Integer blenderLine;

    @Autowired
    private RestTemplate simpleRestTemplate;

    @Scheduled(cron = "${heartBeatCron}")
    @Transactional(rollbackFor = Exception.class)
    public void hearBeat() {
        logger.info("=======================开始发送心跳=======================");
        HeartBeatVO heartBeatVO = new HeartBeatVO();
        heartBeatVO.setBlenderId(blenderId);
        heartBeatVO.setBlenderLine(blenderLine);

        HttpHeaders httpHeadersPush = new HttpHeaders();
        httpHeadersPush.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> sentryRequestEntityPush = new HttpEntity(heartBeatVO, httpHeadersPush);
        ResponseEntity<Integer> responseEntityPush = null;

        String requestUrlPush = blenderUrl + "/dataAcquisition/heartbeat";
        responseEntityPush = simpleRestTemplate.exchange(requestUrlPush, HttpMethod.POST, sentryRequestEntityPush, Integer.class);
        Integer type = responseEntityPush.getBody();
        if(type != null && type == 0){
            //关机
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("shutdown -s -t 00");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info("=======================发送心跳完成=======================");
    }
}
